import { _decorator, ERigidBody2DType, Node, RigidBody, RigidBody2D, sys } from 'cc';
import HeChengDaXiGua_Fruit from "./HeChengDaXiGua_Fruit";

interface HeChengDaXiGua_FruitData {
    level: number;
    x: number;
    y: number;
    rotation: number;
    linearVelocityX: number;
    linearVelocityY: number;
    angularVelocity: number;
}
interface HeChengDaXiGua_GameStorageData {
    high_score: number;
    current_score: number;
    fruits: HeChengDaXiGua_FruitData[];
}

export class HeChengDaXiGua_GameStorage {
    static data: HeChengDaXiGua_GameStorageData = null;
    static defaultValue: HeChengDaXiGua_GameStorageData = null;

    static initData() {
        HeChengDaXiGua_GameStorage.InitDefaultData();

        let dataStr = sys.localStorage.getItem(`HeChengDaXiGua_GameStorage`);
        if (!dataStr || dataStr === "") {
            HeChengDaXiGua_GameStorage.clearData();
        } else {
            HeChengDaXiGua_GameStorage.data = JSON.parse(dataStr);
            HeChengDaXiGua_GameStorage.saveData();
        }

        HeChengDaXiGua_GameStorage.SetEveryData();
    }
    //    // 初始化默认值
    static InitDefaultData() {
        HeChengDaXiGua_GameStorage.defaultValue = {
            high_score: 0,
            current_score: 0,
            fruits: [],
        };
    }
    static SetEveryData() {
        for (let key in HeChengDaXiGua_GameStorage.defaultValue) {
            let defaultValue = HeChengDaXiGua_GameStorage.defaultValue[key];
            let dataValue = HeChengDaXiGua_GameStorage.data[key];
            // console.log(key, defaultValue, dataValue);
            if (dataValue === null || dataValue === undefined) {
                HeChengDaXiGua_GameStorage.data[key] = defaultValue;
            }
        }
        HeChengDaXiGua_GameStorage.saveData();
    }
    static clearData() {
        HeChengDaXiGua_GameStorage.data = { ...HeChengDaXiGua_GameStorage.defaultValue };
    }
    static saveData() {
        let dataStr = JSON.stringify(HeChengDaXiGua_GameStorage.data);
        sys.localStorage.setItem(`HeChengDaXiGua_GameStorage`, dataStr);
    }
    //    // 保存当前所有水果的状态
    static saveFruitsData(fruitLayer: Node, currentScore: number) {
        if (!HeChengDaXiGua_GameStorage.data) {
            HeChengDaXiGua_GameStorage.initData();
        }

        // 如果没有水果，只保存分数
        if (!fruitLayer || fruitLayer.children.length === 0) {
            HeChengDaXiGua_GameStorage.data.current_score = currentScore;
            HeChengDaXiGua_GameStorage.data.fruits = [];
            HeChengDaXiGua_GameStorage.saveData();
            return;
        }

        HeChengDaXiGua_GameStorage.data.current_score = currentScore;
        HeChengDaXiGua_GameStorage.data.fruits = [];

        // 遍历所有水果节点，保存其状态
        fruitLayer.children.forEach(fruitNode => {
            if (!fruitNode || !fruitNode.isValid) return;

            const fruitScript = fruitNode.getComponent(HeChengDaXiGua_Fruit);
            if (!fruitScript) return;

            const rigid = fruitNode.getComponent(RigidBody2D);
            if (!rigid) return;

            // 只保存Dynamic类型的水果（已投放的水果），排除Kinematic类型的水果（当前拖拽的水果）
            if (rigid.type !== ERigidBody2DType.Dynamic) return;

            const fruitData: HeChengDaXiGua_FruitData = {
                level: fruitScript.level,
                x: fruitNode.position.x,
                y: fruitNode.position.y,
                rotation: fruitNode.angle,
                // rotation: fruitNode.eulerAngles.z,
                linearVelocityX: rigid.linearVelocity.x,
                linearVelocityY: rigid.linearVelocity.y,
                angularVelocity: rigid.angularVelocity
            };

            HeChengDaXiGua_GameStorage.data.fruits.push(fruitData);
        });

        HeChengDaXiGua_GameStorage.saveData();
        // console.log(`保存了 ${HeChengDaXiGua_GameStorage.data.fruits.length} 个已投放水果的状态，分数: ${currentScore}`);
    }
    //    // 加载保存的水果数据
    static loadFruitsData(): { fruits: HeChengDaXiGua_FruitData[], currentScore: number } {
        if (!HeChengDaXiGua_GameStorage.data) {
            HeChengDaXiGua_GameStorage.initData();
        }

        return {
            fruits: HeChengDaXiGua_GameStorage.data.fruits || [],
            currentScore: HeChengDaXiGua_GameStorage.data.current_score || 0
        };
    }
    //    // 清除水果数据（开始新游戏时调用）
    static clearFruitsData() {
        if (!HeChengDaXiGua_GameStorage.data) {
            HeChengDaXiGua_GameStorage.initData();
        }

        HeChengDaXiGua_GameStorage.data.fruits = [];
        HeChengDaXiGua_GameStorage.data.current_score = 0;
        HeChengDaXiGua_GameStorage.saveData();
    }
}